package com.example.musicdemo1

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.bumptech.glide.Glide
import com.example.musicdemo1.service.MusicPlayer
import com.google.android.material.tabs.TabLayout
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import com.example.musicdemo1.api.PlaylistApi
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayoutMediator
import com.example.musicdemo1.adapter.MainPagerAdapter

class MainActivity : AppCompatActivity() {
    private lateinit var miniPlayer: View
    private lateinit var miniCoverImage: ImageView
    private lateinit var miniTitleText: TextView
    private lateinit var miniArtistText: TextView
    private lateinit var miniPlayPauseButton: ImageButton
    private lateinit var miniPlaylistButton: ImageButton
    private lateinit var miniNextButton: ImageButton
    
    // 修改API初始化方式
    private val api: PlaylistApi by lazy {
        val logging = HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        }
        
        val client = OkHttpClient.Builder()
            .addInterceptor(logging)
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build()

        Retrofit.Builder()
            .baseUrl("http://121.37.40.55:3000/")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build()
            .create(PlaylistApi::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setupNavigation()
        setupMiniPlayer()
        observePlaybackState()
        loadInitialPlaylist()
    }

    private fun setupNavigation() {
        val viewPager = findViewById<ViewPager2>(R.id.view_pager)
        val tabLayout = findViewById<TabLayout>(R.id.tab_layout)
        
        // 设置ViewPager适配器
        viewPager.adapter = MainPagerAdapter(this)
        
        // 添加标签页
        tabLayout.addTab(tabLayout.newTab().setText("推荐"))
        tabLayout.addTab(tabLayout.newTab().setText("播放器"))
        tabLayout.addTab(tabLayout.newTab().setText("播放列表"))
        
        // 关联TabLayout和ViewPager2
        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            tab.text = when (position) {
                0 -> "推荐"
                1 -> "播放器"
                2 -> "播放列表"
                else -> null
            }
        }.attach()
    }

    private fun setupMiniPlayer() {
        miniPlayer = findViewById(R.id.miniPlayer)
        miniCoverImage = findViewById(R.id.miniCoverImage)
        miniTitleText = findViewById(R.id.miniTitleText)
        miniArtistText = findViewById(R.id.miniArtistText)
        miniPlayPauseButton = findViewById(R.id.miniPlayPauseButton)
        miniPlaylistButton = findViewById(R.id.miniPlaylistButton)
        miniNextButton = findViewById(R.id.miniNextButton)

        val viewPager = findViewById<ViewPager2>(R.id.view_pager)
        
        miniPlayer.setOnClickListener {
            // 切换到播放器页面（索引1）
            viewPager.currentItem = 1
        }

        miniPlayPauseButton.setOnClickListener {
            if (MusicPlayer.isPlaying.value) {
                MusicPlayer.pause()
            } else {
                MusicPlayer.resume()
            }
        }

        miniPlaylistButton.setOnClickListener {
            // 切换到播放列表页面（索引2）
            viewPager.currentItem = 2
        }

        miniNextButton.setOnClickListener {
            MusicPlayer.playNext()
        }
    }

    private fun observePlaybackState() {
        lifecycleScope.launch {
            MusicPlayer.currentMusic.collectLatest { music ->
                music?.let {
                    miniTitleText.text = it.title
                    miniArtistText.text = it.singer
                    Glide.with(this@MainActivity)
                        .load(it.coverImgUrl)
                        .into(miniCoverImage)
                }
            }
        }

        lifecycleScope.launch {
            MusicPlayer.isPlaying.collectLatest { isPlaying ->
                miniPlayPauseButton.setImageResource(
                    if (isPlaying) R.drawable.ic_pause
                    else R.drawable.ic_play
                )
            }
        }
    }

    private fun loadInitialPlaylist() {
        lifecycleScope.launch {
            try {
                val playlist = api.getPlaylist()
                MusicPlayer.setPlaylist(playlist)
            } catch (e: Exception) {
                Log.e("MainActivity", "加载播放列表失败", e)
            }
        }
    }
}